<!--站点列表页-->
<template>
    <div class="wrap">
        <m-page-list
                :page="page"
                :total="page.total"
                :option="option"
                :table-data="tableData"
                :table-loading="tableLoading"
        >
            <template #hLSlot >
                <div class="tips">
                    注意：<br>
                    1.班车途经站点不同时，建议分开不同的班车，最好不要在班车站点(讫地)表录入多个班车站点(讫地)。<br>
                    2.如果在【班车站点(讫地)表】录入多个班车站点(讫地)时，需要确保多个班车站点(讫地)的去程班车站点一致、回程班车站点一致、各套票票价一致，否则可能售出班车不到达的站点。<br>
                    3.在【班车站点】功能中站点类型为”站点(讫地)”时，不会出现在购票的上车站点和下车站点选项中，它主要用途是标识该站点(讫地)构成班车行驶路线中其中的一个途经节点的作用。
                </div>
            </template>
        </m-page-list>
        <m-dialog-form ref="dialogRef" :data="dialogData" v-model:show="dialogShow" :option="dialogOption" @confirm="dialogConfirm" ></m-dialog-form>
    </div>

</template>

<script setup>

  import {defineProps,watch} from 'vue'
  //组件
  import MPageList from '@/components/PageList'
  import MDialogForm from '@/components/DialogForm/DialogForm'
  //请求
  import {getShuttleStop, addShuttleStop,editShuttleStop,delShuttleStop,delShuttleStopBySid,getShuttleDirection,getStop,getSchool,publicAllData} from '@/request/api/basicData'

  import {usePageList} from "./relPage";
  //引用类型字段参数
  import {refOpt} from "../const";

  const props = defineProps(['shuttleData']);

  let shuttleSeatId ='';
  let opts = {
    auth_id: 'shuttleStop',
    getApi: getShuttleStop,addApi:addShuttleStop,editApi:editShuttleStop,delApi:delShuttleStop,
    idKey: ['shuttle_id','stop_id','shuttle_direction_id'],
    defQuery: '',
    cols: [
      {prop: 'shuttle_name',label: '班车名称' },
      {prop: 'shuttle_direction_name',label: '班车方向名称' },
      {prop: 'stop_name',label: '班车站点名称' },
      {prop: 'sort',label: '序号', },
      {prop: 'sale_minimum',label: '可售最少数', },
      {prop: 'path_type',label: '路径类型', },
      {prop: 'departure_time',label: '发车时间', },
      {prop: 'arrive_time',label: '到达时间'},
      {prop: 'mark',label: '说明', },
      {prop: 'is_used',label: '使用标识',type: 'bool' },
    ],
    confirmCallback: () => publicAllData(shuttleSeatId),
    deleteCallback: () => publicAllData(shuttleSeatId)
  };
  let {option,tableLoading,tableData,query,page,dialogShow,dialogData,dialogOption,defDialogData,dialogRef,isAppend,isDelete,isEdit,
    dialogConfirm,
    getDataList,} = usePageList(opts);

  defDialogData.is_used = true;

  watch(() => props.shuttleData, (newVal) => {
    if (newVal){
      let {shuttle_id,shuttle_name,shuttle_seat_id} = newVal;
      query.shuttle_id = shuttle_id;
      defDialogData.shuttle_id = shuttle_id;
      defDialogData.shuttle_name = shuttle_name;
      getDataList();
      shuttleSeatId = shuttle_seat_id || shuttle_id
    }
  },{immediate: true});

  /*option.hRBtns = [
    {title: '新增站点',id: 'stop',type: 'primary',event: () => showDialog('add','stop')},
    {title: '新增站点',id: 'school',type: 'primary',event: () => showDialog('add','school')},
    {title: '清空',id: 'build',type: 'primary',event: clearAll}
  ]*/
  option.colBtns.splice(0,1);
 /* option.colBtns.unshift(
    {title: '编辑',id: 'edit',type: 'primary',event:(scope) => showDialog('edit','',scope)},
  )*/

  prepare()

  const fieldList =  [
    {field_id: 'shuttle_id',label: '班车编号',type: 'text',col:2,disabled: true ,required: true},
    {field_id: 'shuttle_name',label: '班车名称',type: 'reference',col:2 ,disabled: true ,required: true},
    {...refOpt.stop_id,col:2,required: true},
    {...refOpt.stop_name,editDisabled: true,col:2,required: true},

    {label: '站点(讫地)编号',field_id: 'stop_id',type: 'reference',col: 2,disabled: true,required: true},
    {label: '站点(讫地)名称',field_id: 'stop_name',editDisabled: true,type: 'reference',col: 2,refUrl: getSchool,required: true,
      refCols: [
        {prop: 'school_id', label: '站点(讫地)编号',},
        {prop: 'school_name', label: '站点(讫地)名称',},
      ],entityKey: 'school_name',valueKey: [{'stop_id':'school_id'},{'stop_name': 'school_name'}],
      searchField: ['name']},

    {...refOpt.shuttle_direction_id,col:2,required: true},
    {...refOpt.shuttle_direction_name,editDisabled: true,col:2,required: true,valueKey: ['shuttle_direction_id',{shuttle_direction_name: `${props.shuttleData.shuttle_type === '定制'? 'custom_shuttle_direction_name' : 'shuttle_direction_name'}`}]},
    {field_id: 'sort',label: '序号',type: 'number',col:2 },
    {field_id: 'sale_minimum',label: '可售最少数',type: 'number',col:2 },
    {field_id: 'departure_time',label: '发车时间',type: 'time' ,col:2},
    {field_id: 'arrive_time',label: '到达时间',type: 'time',col:2 },
    {field_id: 'mark',label: '说明',type: 'textarea',col:4 },
    {field_id: 'is_used',label: '使用标识',type: 'bool' ,col:2},
  ]

  /**
   * 显示弹窗
   * @param type 弹窗类型：add新增、edit编辑
   * @param path 站点类型：school站点、stop普通站点
   * @param data 编辑数据：
   */
  function showDialog(type,path,data) {
    if ( (type === 'add' && !isAppend.value) || (type === 'edit' && !isEdit.value)){
      ElMessage({
        type: 'warning',
        message: `抱歉，您没有权限${type === 'add' ? '新增': '编辑'}该模块数据`
      })
      return
    }
    let list = fieldList,
      row = data && data.row,
      value = {};

    defDialogData.path_type = path === 'school' ? '站点(讫地)' : '站点';
    if(row) path = row.path_type === '站点(讫地)' ? 'school' : 'stop';

    //设置弹窗标题
    let title = (type === 'add' ? '新增': '编辑') + (path === 'school' ? '站点(讫地)站点': '站点');
    list = list.filter((item,index) => {
      if (item.editDisabled) item.disabled = type === 'edit';

      if (type === 'edit'){
        let val = row[item.show_field || item.field_id]
        val && (value[item.field_id] = val)
      }else {
        value = defDialogData;
      }
      /*if (item.field_id === 'stop_id'){
        item = path === 'school' ? {...refOpt.school_id,field_id: 'stop_id'} : {...refOpt.stop_id,}
      }
      if (item.field_id === 'stop_name'){
        item = path === 'school' ? {...refOpt.school_name,field_id: 'stop_name'} : {...refOpt.stop_name,}
      }*/
      if (path === 'school') {
        return ![2,3].includes(index);
      }else {
        return ![4,5].includes(index);
      }
    })
    dialogOption.title = title;
    dialogData.value = value;
    dialogShow.value = true;
    dialogOption.fieldList = list;
  }

  //删除所有站点
  function clearAll(){
    if (!isDelete.value){
      ElMessage({
        type: 'warning',
        message: '抱歉，您没有权限删除该模块数据'
      })
      return
    }
    ElMessageBox.confirm('确定删除该班次所有站点？', '清空', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm'){
          delShuttleStopBySid(query.shuttle_id).then(res => {
            if (res.errcode !== 0)return;
            ElMessage({
              type: 'success',
              message: `删除成功`,
            });
            getDataList();
            publicAllData(shuttleSeatId);
          })
        }
      },
    })
  }

  function dialogConfirm_(obj) {

    let {data,option} = obj,
      isAdd = option.title.indexOf('新增') >= 0 ;
    let pm = new Promise(resolve => {
      if (isAdd){
        addShuttleStop(data).then(res => {
          if (res.errcode !== 0)return;
          resolve(data);
        })
      }else {
        editShuttleStop(data).then(res =>{
          if (res.errcode !== 0)return;
          resolve(data);
        })
      }
    });

    pm.then(() => {
      ElMessage({
        message: option.title+'成功',
        type: 'success',
      })
      dialogRef.value.close();
      getDataList();

    })
  }

  function prepare() {
    let arr = []
    isAppend.value && arr.push({title: '新增站点',id: 'stop',type: 'primary',event: () => showDialog('add','stop')},
      {title: '新增站点(讫地)',id: 'school',type: 'primary',event: () => showDialog('add','school')})
    isDelete.value && arr.push({title: '清空',id: 'build',type: 'primary',event: clearAll})
    option.hRBtns = arr;

    isEdit.value && option.colBtns.unshift(
      {title: '编辑',id: 'edit',type: 'primary',event:(scope) => showDialog('edit','',scope)},
    )
  }
</script>

<style scoped lang="less">
    .wrap{
        height: 100%;
        display: flex;
        flex-direction: column;
        .tips{
            padding-right: 16px;
        }
        ::v-deep{
            .layout-header{
                padding: 0;
            }
            .layout-main{
                padding: 4px 0 0;
            }
        }
    }

</style>
